package com.example.demo.model;

import com.example.demo.dao.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by huxin on 2017/7/31.
 */

@Component
public class UserServiceImpl implements UserService<User> {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void create(String name, Integer age) {
        jdbcTemplate.update("INSERT INTO User(name, age) VALUES(?, ?)", name, age);
    }

    @Override
    public void deleteByName(String name) {
        jdbcTemplate.update("DELETE FROM User WHERE name = ? ", name);
    }

    @Override
    public void deleteById(Long id) {
        jdbcTemplate.update("DELETE FROM User WHERE id = ? ", id);
    }

    @Override
    public void deleteAllUsers() {
        jdbcTemplate.update("DELETE FROM User");
    }

    @Override
    public Integer getAllUsersCount() {

        return jdbcTemplate.queryForObject("SELECT COUNT(1) FROM User", Integer.class);
    }

    @Override
    public List<User> getAllUsers(){
        return jdbcTemplate.query("SELECT id, name, age FROM User", new UserRowMapper());
    }

    @Override
    public User getUserById(Long id) {
        return jdbcTemplate.queryForObject("SELECT id, name, age FROM User WHERE id = ?", new UserRowMapper(), id);
    }

    @Override
    public void update(User user) {
        jdbcTemplate.update("UPDATE User SET name = ?, age = ? WHERE id = ?", user.getName(), user.getAge(), user.getId());
    }


    public class UserRowMapper implements RowMapper<User>{
        @Override
        public User mapRow(ResultSet resultSet, int i) throws SQLException {
            return new User(resultSet.getLong("id"),
                    resultSet.getString("name"),
                    resultSet.getInt("age"));
        }
    }
}
